package com.ms.oschina.ui.activity;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;

import com.ms.oschina.R;
import com.ms.oschina.base.BaseActivity;
import com.ms.oschina.fragment.ContentFragment;
import com.ms.oschina.fragment.LeftMenuFragment;
import com.ms.oschina.util.UiUtils;

public class HomeActivity extends BaseActivity {
	private static final String FRAME_LEFTTAG = "frame_lefttag";
	private static final String FRAME_CONTENTTAG = "frame_contenttag";
	private LeftMenuFragment leftFragment;

	@Override
	protected int getLayoutId() {
		return R.layout.activity_home;
	}
	@Override
	protected Boolean isCanSwipe() {
		return false;
	}
	
	@Override
	protected void initData() {
		android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();

		// 将侧滑栏的fragment替换到侧滑栏的容器的布局文件中
		leftFragment = new LeftMenuFragment();
		transaction.replace(R.id.home_left_drawer, leftFragment, FRAME_LEFTTAG);// 添加标记方便查找

		ContentFragment contentFragment = new ContentFragment();
		transaction.replace(R.id.home_content_frame, contentFragment,
				FRAME_CONTENTTAG);// 添加标记方便查找

		transaction.commit();
	}

	public void replaceContent(Fragment fragment) {
		android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();
		transaction
				.replace(R.id.home_content_frame, fragment, FRAME_CONTENTTAG);// 添加标记方便查找
		transaction.commit();
	}

	public void closeDrawer() {
		getmDrawerLayout().closeDrawer(Gravity.LEFT);
	}

	public LeftMenuFragment getFragmentLeft() {
		Fragment left_fragment = getSupportFragmentManager().findFragmentByTag(
				FRAME_LEFTTAG);
		return (LeftMenuFragment) left_fragment;
	}

	public ContentFragment getFragmentContent() {
		Fragment content_fragment = getSupportFragmentManager()
				.findFragmentByTag(FRAME_CONTENTTAG);
		return (ContentFragment) content_fragment;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		int itemId = item.getItemId();
		if (itemId == R.id.action_search) {
			Intent intent = new Intent(HomeActivity.this,
					SkillsCakeActivity.class);
			startActivity(intent);
			return true;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	private long pressedTime;

	/**
	 * 3秒内连续按下两次推出应用程序。
	 */
	@Override
	public void onBackPressed() {
		// 记录按下的位置
		// 得到当前时间
		long currentTimeMillis = System.currentTimeMillis();
		if (currentTimeMillis - pressedTime < 3000) {
			// 完全推出
			System.exit(0);
		} else {
			UiUtils.showToast("再按一次退出程序");
			pressedTime = currentTimeMillis;
		}
	}
	@Override
	protected boolean isHomeActivity() {
		return true;
	}

}
